const config = require('../config/config')
const crypto = require('crypto')
class Tool {
  static menusCompanyStatus = {
    '-1': '未通过审核',
    0: '未审核',
    1: '通过审核'
  }

  static menusCompanyStatusColor = {
    '-1': 'red',
    0: 'grey',
    1: 'cyan'
  }

  static menusActorStatus = {
    '-1': '未通过审核',
    0: '未审核',
    1: '审核成功'
  }

  static menusActorStatusColor = {
    '-1': 'red',
    0: 'grey',
    1: 'cyan'
  }

  static errorMsg(errArr, type) {
    if (type === 'req') {
      if (errArr.length > 0) {
        return errArr[0].msg
      }
    }
    return ''
  }

  static encrypt(data) {
    let password = crypto.createHash('md5').update(data).digest('hex')
    return crypto
      .createHash('md5')
      .update(config.password.secret + password)
      .digest('hex')
  }

  static validatorError(errors) {
    return {
      code: 422,
      msg: this.errorMsg(errors.array(), 'req'),
      errors: errors.array()
    }
  }

  static exceptionError(err) {
    const uniqueConstraints = {
      login_name: '用户登录名',
      role_name: '角色名',
      mobile: '手机号码',
      email: '电子邮件地址'
    }
    if (err['name'] === 'SequelizeUniqueConstraintError') {
      let dup = Object.keys(err['fields'])[0]
      return {
        code: 500,
        msg: uniqueConstraints[dup] + '【' + err['fields'][dup] + '】已经存在'
      }
    } else {
      return {
        code: 500,
        msg: '数据库错误',
        errors: err
      }
    }
  }

  static authCooperationSign(req, secret) {
    let flgSign = false
    if (req.headers['x-timestamp'] && req.headers['x-sign']) {
      let signBase = 'timestamp=' + req.headers['x-timestamp'] + '&company=weapp&secret=' + secret
      if (crypto.createHash('md5').update(signBase).digest('hex') === req.headers['x-sign']) {
        flgSign = true
      }
    }
    return flgSign
  }

  static authApp(req) {
    let flgSign = false
    let token =
      req.body.openid ||
      req.query.openid ||
      req.headers['openid'] ||
      req.body.deviceId ||
      req.query.deviceId ||
      req.headers['deviceId']
    if (token) {
      flgSign = true
    }
    return flgSign && this.authCooperationSign(req, 'SrNI71HOYbnR')
  }

  static isJsonString(str) {
    try {
      JSON.parse(str)
    } catch (e) {
      return false
    }
    return true
  }

  static prefixInteger(num, length) {
    return (Array(length).join('0') + num).slice(-length)
  }

  static imagesApi2Db(imageList) {
    let arrImage = []
    if (imageList && Tool.isJsonString(imageList)) {
      let images = JSON.parse(imageList)
      for (let index = 0; index < images.length; index++) {
        const image = images[index]
        arrImage.push({
          name: image.name,
          url: image.url.replace(new RegExp(config.resource_domain, 'g'), '')
        })
      }
    }
    return arrImage
  }

  static imagesDb2Api(imageList) {
    let arrImage = []
    if (imageList && Tool.isJsonString(imageList)) {
      let images = JSON.parse(imageList)
      for (let index = 0; index < images.length; index++) {
        const image = images[index]
        arrImage.push({
          name: image.name,
          url: config.resource_domain + image.url
        })
      }
    }
    let item = {}
    item.images = arrImage
    if (arrImage.length > 0) {
      item.pic = arrImage[0].url
    } else {
      item.pic = ''
    }
    return item
  }

  static deepClone(obj) {
    return JSON.parse(JSON.stringify(obj))
  }

  static getCoordWD(scenicAddress, scenicName, audioName, type) {
    let reg = /.+?(省|市|自治区|自治州|县|区)/g
    let addrArr = scenicAddress.match(reg)
    let addr = ''
    if (addrArr) {
      addrArr.some(item => {
        if (item.endsWith('市') || item.endsWith('自治州') || item.endsWith('县')) {
          addr += item
          return true
        }
      })
    }
    let wd =
      addr +
      scenicName +
      audioName
        .replace('总述', '')
        .replace(/\([\u4e00-\u9fa5]+\)/g, '')
        .replace(/（[\u4e00-\u9fa5]+）/g, '')
    console.log(wd)
    if (type === 'baidu') {
      wd = encodeURIComponent(
        scenicName +
          audioName
            .replace('总述', '')
            .replace(/\([\u4e00-\u9fa5]+\)/g, '')
            .replace(/（[\u4e00-\u9fa5]+）/g, '')
      )
      wd += '&rg=' + encodeURIComponent(addr) + '&t=1'
    } else {
      wd = encodeURIComponent(wd)
    }
    return wd
  }

  static bdEncrypt(ggLng, ggLat) {
    var X_PI = (Math.PI * 3000.0) / 180.0
    var x = ggLng
    var y = ggLat
    var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * X_PI)
    var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * X_PI)
    var bdLng = z * Math.cos(theta) + 0.0065
    var bdLat = z * Math.sin(theta) + 0.006
    return { bd_lat: bdLat.toFixed(6), bd_lng: bdLng.toFixed(6) }
  }

  static getCity(addr) {
    const reg = /.+?(省|市|自治区|自治州|县|区)/g
    const addrArr = addr.match(reg)
    let ret = ''
    if (addrArr) {
      addrArr.some(item => {
        if (item.endsWith('市') || item.endsWith('自治州')) {
          ret = item.replace('市', '').replace('自治州', '')
          return true
        }
      })
    }
    return ret
  }

  static randomPassword(length) {
    var str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    var result = ''
    for (var i = length; i > 0; --i) {
      result += str[Math.floor(Math.random() * str.length)]
    }
    return result
  }

  static getVerifyCode(length) {
    var str = '0123456789'
    var result = ''
    for (var i = length; i > 0; --i) {
      result += str[Math.floor(Math.random() * str.length)]
    }
    return result
  }

  static callSmsApi(phone, verifyCode) {
    const qiniu = require('qiniu')
    let accessKey = config.storage.accessKey
    let secretKey = config.storage.secretKey
    let reqBody = {
      template_id: '1288429229171552256',
      mobile: phone,
      parameters: {
        code: verifyCode
      }
    }
    let mac = new qiniu.auth.digest.Mac(accessKey, secretKey)
    return new Promise((resolve, reject) =>
      qiniu.sms.message.sendSingleMessage(reqBody, mac, function(respErr, respBody,
        respInfo) {
        if (respErr) {
          console.log(respErr)
          reject(respErr)
        } else {
          if (respInfo.statusCode === 200) {
            resolve(reqBody)
          } else {
            reject(respInfo)
          }
        }
      })
    )
  }
}
module.exports = Tool
